package com.coder520.mamabike.common.rest;

import com.coder520.mamabike.cache.CommonCacheUtil;
import com.coder520.mamabike.common.constants.Constants;
import com.coder520.mamabike.common.exception.MaMaBikeException;
import com.coder520.mamabike.user.entity.UserElement;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;

/**
 * @author ZhouGuoWei
 * @date 2018/11/18 16:38
 * @Annotation 所有控制层的父类
 */
@Slf4j
public class BaseController {

    @Autowired
    private CommonCacheUtil cacheUtil;

    /**
     * 从缓存中获取当前用户
     * @return ue or null
     */
    protected UserElement getCurrentUser(){
        HttpServletRequest request =((ServletRequestAttributes) RequestContextHolder.currentRequestAttributes()).getRequest();
        String token = request.getHeader(Constants.REQUEST_TOKEN_KEY);
        if(StringUtils.isNotBlank(token)){
            try {
               UserElement ue = cacheUtil.getUserByToken(token);
               return ue;
            } catch (MaMaBikeException e) {
                log.error("从缓存中获取当前用户失败",e);
                return null;
            }
        }
        return null;
    }
}
